import { Component, OnInit, ViewChild, TemplateRef, ChangeDetectorRef, ElementRef, ChangeDetectionStrategy } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { format } from 'date-fns';
import { SFSchema, SFComponent, SFCheckboxWidgetSchema, WidgetRegistry } from '@delon/form';
import { SupDic, HttpService, GridComponent } from 'lbf';
import { STColumn, STComponent, STPage, STChange, STData } from '@delon/abc';

import { NzMessageService, NzModalService, NzModalRef, NzListItemComponent } from 'ng-zorro-antd';
import { Template } from '@angular/compiler/src/render3/r3_ast';
import { DatePipe } from '@angular/common';
import { Lbka03WidgetComponent } from '@shared';


@Component({
  selector: 'app-xtgn-jzmxcx',
  templateUrl: './jzmxcx.component.html',
  styleUrls: ['./jzmxcx.component.less'],
  providers: [DatePipe],
})
export class XtgnJzmxcxComponent implements OnInit {
  constructor(private lbservice: HttpService,
    private supdic: SupDic,
    public message: NzMessageService,
    private modalService: NzModalService,
    private DatePipe: DatePipe,
    private wdigetreg: WidgetRegistry,
  ) {
    wdigetreg.register(Lbka03WidgetComponent.KEY, Lbka03WidgetComponent)
  }

  dateRange = [];
  shown = true;
  expandForm = false;
  fundvisible = false;
  costvisible = false;
  drvisible = false;
  textvisible = false;
  popvisible = false;
  tplModal: NzModalRef;
  list: any[] = [null];
  inputValue: string;
  person: string;
  fundData = [];
  formData = [];
  arr =[];
  arrA =[];
  arrB =[];

  loading = false;

  fundPieData: STData[] = [
    {
      x: '现金',
      y: 100
    },
    {
      x: '其他',
      y: 1231,
    },
  ]

  costPieData: STData[] = [
    {
      x: '现金',
      y: 100
    },
    {
      x: '其他',
      y: 1231,
    },
  ]
  demoData = [
        { value: 251, type: '大事例一', name: '子事例一' },
        { value: 1048, type: '大事例一', name: '子事例二' },
        { value: 610, type: '大事例二', name: '子事例三' },
        { value: 434, type: '大事例二', name: '子事例四' },
        { value: 335, type: '大事例三', name: '子事例五' },
        { value: 250, type: '大事例三', name: '子事例六' }
      ];
  data: any[] = []

  stpage: STPage = {
    total: true,
    show: true, // 显示分页
    front: false // true是前端分页，false后端控制分页
  };
  stchange: STChange = {
    type: "pi",
    pi: 1,
    ps: 10,
    total: 0,
  }
  fund = {
    total: `&yen ${this.fundPieData.reduce((pre, now) => now.y + pre, 0).toFixed(2)}`,
    format: (val: number) => {
      return `&yen ${val.toFixed(2)}`;
    },
  }
  cost = {
    total: `&yen ${this.costPieData.reduce((pre, now) => now.y + pre, 0).toFixed(2)}`,
    format: (val: number) => {
      return `&yen ${val.toFixed(2)}`;
    },
  }
  stvisible = false

  para = { aa: 1 }
  CKC009 = null
  params = {
    query: "JZCX_query",
    summary: 'ybcx_xmhz',
    cost: 'ybcx_fyxq',
    fund: 'ybcx_jjfl',
    CostClassification: 'ybcx_fyfl',
    disease: 'ybcx_jbfl',
    save:'MXCX_save',
    conditionQuery:'MXCX_query',
    delCondition:'MXCX_del',
    share:'MXCX_share',
    form: {
      'CKC009': this.CKC009
    }
  }
  isVisible = false

  data1: any[] = []
  schema: SFSchema = {
    properties: {
      'start': {
        title: '开始日期',
        type: 'string',
        ui: { widget: 'date' }
      },
      end: {
        title: '结束日期',
        type: 'string',
        ui: { widget: 'date' }
      },
    }, ui: {
      "spanLabelFixed": 120,
      "grid": {
        "span": 8
      }
    }
  }
  columns: STColumn[] = [
    { title: '姓名', index: 'AAC003', width: 100, fixed: 'left' },
    { title: '身份证', index: 'AAC002', width: 100 },
    {
      title: '性别', index: 'AAC004', type: 'tag',
      tag: {
        1: { text: '男', color: 'green' },
        2: { text: '女', color: 'red' }
      },
      width: 50,
    },
    { title: '年龄', index: 'EAC029', type: 'number', width: 50 },
    { title: '所属医共体', index: 'AKE500', dic: 'AKE500', width: 100 },
    { title: '就诊机构', index: 'AKB002', dic: 'AKB002', width: 100 },
    { title: '机构类别', index: 'AKB025', dic: 'AKB025', width: 100 },
    { title: '就诊类型', index: 'AKC001', dic: 'AKC001', width: 100 },
    { title: '结算日期', index: 'AAE070', width: 100 },
    { title: '入院日期', index: 'AKC041', width: 100 },
    { title: '总费用', index: 'AKC046', type: 'currency', width: 100 },
    { title: '药品费用', index: 'AKC150', type: 'currency', width: 100 },
    { title: '医保费用', index: 'AKC048', type: 'currency', width: 100 },
    { title: '基金支出', index: 'AKC270', type: 'currency', width: 100 },
    { title: '个人现金', index: 'AKC276', type: 'currency', width: 100 },
    { title: '结算区域', index: 'AKE056', dic: 'AKE056', width: 100 },
    { title: '医生姓名', index: 'CKC017', width: 100 },
    { title: '就诊科室', index: 'BKE005', width: 100 },
    { title: '社保编号', index: 'AAC001', width: 100 },
    { title: '退费标志', index: 'AKE054',type:'tag' ,tag:{
      0:{text:'未退费',color:'red'},
      1:{text:'已退费',color:'blue'},
      2:{text:'未知',color:'black'}
    }, width: 100 },
    { title: '扣款金额', index: 'AKC290',type: 'currency', width: 100 },
    {
      title: '操作区', index: 'operator',
      buttons: [
        {
          text: '查看',

          click: (record) => {

            this.CKC009 = record.CKC009
            this.params.form = {
              'CKC009': this.CKC009
            }
            const Modal = this.modalService.create({
              nzTitle: "明细",
              nzOnCancel: () => {
                this.fundvisible = false
                this.costvisible = false
                Modal.destroy()
              },
              nzWidth: 1000,
              nzCancelText: null,
              nzClosable: true,
              nzOkText: null,
              nzContent: this.tplContent,
            })

            this.stvisible = true
          }
        }
      ],
      fixed: 'right', width: 100
    }
  ]

  columns3: STColumn[] = [
    { title: '基金分类', index: 'BKA157', dic: 'BKA157' },
    { title: '基金金额', index: 'AAE019' },
  ]
  columns4: STColumn[] = [
    { title: '费用类别', index: 'AKA005', dic: 'AKA005' },
    { title: '明细类别', index: 'AKA003', dic: 'AKA003' },
    { title: '总金额', type: 'currency', index: 'AKC057' },
    { title: '自理', type: 'currency', index: 'AKC058' },
    { title: '自费', type: 'currency', index: 'AKC059' },
  ]
  columns1: STColumn[] = [
    { title: '中心编码', index: 'AKC053' },
    { title: '名称', index: 'AKC052' },
    { title: '药品诊疗', index: 'AKA003', dic: 'AKA003' },
    { title: '中心名称', index: 'AKE036' },
    { title: '数量', type: 'number', index: 'AKC056' },
    { title: '金额', type: 'currency', index: 'AKC057' },
    { title: '医保范围金额', type: 'currency', index: 'YBFWJE' },
  ]
  columns2: STColumn[] = [
    { title: '中心编码', index: 'AKC053', width: 100 },
    { title: '处方日期', index: 'BKE004', width: 100 },
    { title: '项目名称', index: 'AKC052', width: 200 },
    { title: '医保费用', type: 'currency', index: 'AKC057', width: 100 },
    { title: '数量', type: 'number', index: 'AKC056', width: 100 },
    { title: '规格', index: 'AKE025', width: 100 },
    { title: '单位', index: 'AKE024', width: 100 },
    { title: '目录备注', index: 'AKC202', width: 200 },
    { title: ' 开方数量', index: 'AKC430', type: 'number', width: 100 },
    { title: ' 贴数', index: 'BKC014', type: 'number', width: 100 },
    { title: ' 中心项目名称', index: 'AKE036', width: 100 },
    { title: ' 出院带药', index: 'AKC434', width: 100 },
    { title: ' 单价', index: 'AKC055', type: 'number', width: 100 },
    { title: ' 限价', index: 'AKC228', type: 'number', width: 100 },
    { title: ' 金额', index: 'AKC057', type: 'currency', width: 100 },
    { title: ' 自付比例', index: 'AKB040', width: 100 },
  ]
  columns5: STColumn[] = [
    { title: '疾病序号', index: 'AKC187', dic: 'AKC187' },
    { title: '疾病代码', index: 'AKC188' },
    { title: '疾病名称 ', index: 'AKC189' },
  ]

  @ViewChild('sf', { static: false }) sf: SFComponent
  @ViewChild('st', { static: false }) st: GridComponent
  @ViewChild('st1', { static: false }) st1: STComponent
  @ViewChild('stfund', { static: false }) stfund: GridComponent
  @ViewChild('costst', { static: false }) stcost: GridComponent
  @ViewChild('tplContent', { static: false }) tplContent: TemplateRef<any>
  @ViewChild('search', { static: false }) searchContent: TemplateRef<any>;
  @ViewChild('listitem',{static:false}) listitem: NzListItemComponent;
  ngOnInit() {
  
    this.ConditionQuery();

    this.arr = this.supdic.getSFDic('AKB101');
    this.arrA = this.supdic.getSFDic('AKB101A');
    this.arrB = this.supdic.getSFDic('AKB101B');
  }

  expand() {
    this.expandForm = !this.expandForm
    if (this.expandForm) {
      console.log("展开")
      this.schema = {
        properties: {
          'start': {
            title: '开始日期',
            type: 'string',
            // tslint:disable-next-line: no-object-literal-type-assertion
            ui: { widget: 'date' }
          },
          end: {
            title: '结束日期',
            type: 'string',
            // tslint:disable-next-line: no-object-literal-type-assertion
            ui: { widget: 'date' }
          },
          'AKE500': {
            title: '所属健共体',
            type: 'string',
            enum: this.supdic.getSFDic('AKE500'),
            ui: {
              widget: 'select',
              allowClear: true,
              change:(value)=>{

                  if(value ==='A')
                  {
                     const property = this.sf.getProperty('/AKB101')!;
                      property.schema!.enum = this.arrA;
                      property.resetValue(null,true);
                  }else if(value ==='B')
                  {
                    const property = this.sf.getProperty('/AKB101')!;
                    property.schema!.enum = this.arrB;
                    property.resetValue(null,true);
                  }else{
                    const property = this.sf.getProperty('/AKB101')!;
                    property.schema!.enum = this.arr;
                    property.resetValue(null,true);

                  }

              }
            }
          },
          'AKB101':{
            title: '医疗机构',
            type: 'string',
            enum: this.arr,
            ui: {
              widget: 'select',
              allowClear: true,
            
            }
          },
          'AAE140': {
            title: '险种类型',
            type: 'string',
            enum: this.supdic.getSFDic('AAE140'),
            // tslint:disable-next-line: no-object-literal-type-assertion
            ui: {
              widget: 'select',
              allowClear: true,
             
            } as SFCheckboxWidgetSchema,
          },
          'AKB025': {
            title: '医疗机构类别',
            type: 'string',
            enum: this.supdic.getSFDic('AKB025'),
            ui: {
              widget: 'select',
              allowClear: true,
             

            }

          },
          'AKE056': {
            title: '结算区域',
            type: 'string',
            enum: this.supdic.getSFDic('AKE056'),
            ui: {
              widget: 'select',
              allowClear: true,
             

            }

          },
          'AKC001': {
            title: '就诊类型',
            type: 'string',
            enum: this.supdic.getSFDic('AKC001'),
            ui: {
              widget: 'select',
              mode: 'multiple',
             
            }

          },
          'BKC231': {
            title: '疾病搜索',
            type: 'string',
            ui: {
              widget: 'lbka03'
            }
          },
          'CKC017': {
            title: '医生搜索',
            type: 'string',
           
          },
          'BKE005': {
            title: '科室搜索',
            type: 'string',
          },
          'GRSS': {
            title: '个人搜索',
            type: 'string',
            ui: {
              placeholder: '姓名或身份证或社保编号或门诊住院号',

            }
          },

          'AKC100': {
            title: '医保待遇类别',
            type: 'string',
            enum: this.supdic.getSFDic('AKC100'),
            ui: {
              widget: 'select',
              mode: 'multiple',
              grid: {
                span: 16
              }
            }
          },

          'EAC039': {
            title: '职工年龄分布',
            type: 'string',
            enum:
              [
                { label: '18-39岁', value: '1' },
                { label: '45-50岁', value: '2' },
                { label: '51-60岁', value: '3' },
                { label: '61-70岁', value: '4' },
                { label: '>70岁', value: '5' },

              ],

            // tslint:disable-next-line: no-object-literal-type-assertion
            ui: {
              widget: 'checkbox',
              span: 4, // 指定每一项 8 个单元的布局
              checkAll: true,
              grid: {
                span: 24
              }
            } as SFCheckboxWidgetSchema,
          },

          'EAC049': {
            title: '城乡年龄分布',
            type: 'string',
            enum:
              [
                { label: '0-12月', value: '1' },
                { label: '1-3岁', value: '2' },
                { label: '4-17岁', value: '3' },
                { label: '18-50岁', value: '4' },
                { label: '51-60岁', value: '5' },
                { label: '61-70岁', value: '6' },
                { label: '>70岁', value: '7' },

              ],
            // tslint:disable-next-line: no-object-literal-type-assertion
            ui: {
              widget: 'checkbox',
              span: 4, // 指定每一项 8 个单元的布局
              checkAll: true,
              grid: {
                span: 24
              }
            } as SFCheckboxWidgetSchema,
          },

        },
        ui: {
          "spanLabelFixed": 120,
          "grid": {
            "span": 8
          }
        }
      }
    } else {
      console.log("收起")
      this.schema = {
        properties: {
          'start': {
            title: '开始日期',
            type: 'string',
            // tslint:disable-next-line: no-object-literal-type-assertion
            ui: { widget: 'date' }
          },
          end: {
            title: '结束日期',
            type: 'string',
            // tslint:disable-next-line: no-object-literal-type-assertion
            ui: { widget: 'date' }
          },
        }, ui: {
          "spanLabelFixed": 120,
          "grid": {
            "span": 8
          }
        }
      }
    }
  }

  // 查询数据
  getData() {

    const value = this.sf.value

    if (value.start !== undefined) {
      value.start = this.DatePipe.transform(value.start, 'yyyyMMdd')
    }
    if (value.end !== undefined) {
      value.end = this.DatePipe.transform(value.end, 'yyyyMMdd')
    }
    this.st.reload(value)
    console.log(value)

  }
  reset() {
    this.sf.reset();
    this.formData = [];
  }
  // 表单改变
  change(e: any) {
    console.log(e)
    if (e.type === 'pi' && e.pi !== 1) {
      this.st.loading = true
      const para = this.para
      this.lbservice.lbservice(this.params.query, { para, page: { 'PAGESIZE': 10, 'PAGEIDX': e.pi } }).then(
        (resdata) => {
          if (resdata.code > 0) {
            this.data = resdata.message.list
            this.stchange.pi = e.pi
            this.stchange.total = resdata.page.COUNT
            this.st.loading = null
            console.log("loading", this.st.loading)
          } else {
            this.message.error("查询失败")
            this.st.loading = null
          }
        }
      )
    }

  }
  change1(e: any) {
    console.log(e)
  }
  // 对话框内容  

  // this.data1 = []
  //  this.st1.loading = true
  // this.columns0 = this.columns4
  // this.st1.scroll.x =this.columns4.length*100 +'px'
  // this.lbservice.lbservice(this.params.CostClassification, { para: { CKC009: this.CKC009 }, page: { 'PAGESIZE': 10, 'PAGEIDX': 1 } }).then(
  //   (resdata) => {
  //     if (resdata.code > 0) {

  //       this.data1 = resdata.message.list
  //       this.stchange.total = resdata.page.COUNT
  //       this.st.reload()
  //     }
  //   })
  //  this.st1.loading = false



  // 基金饼状图
  fundClick(e: any) {
    console.log(this.stfund.data)
    this.fundPieData = [];
    this.fundvisible = true
    this.stfund.data.map((d) => {
      const x = d._values[0].text
      const y = d.AAE019
      this.fundPieData.push({ x, y })
    })
    this.fund.total = `&yen ${this.fundPieData.reduce((pre, now) => now.y + pre, 0).toFixed(2)}`
    console.log('fundPieData :', this.fundPieData);
  }

  // 费用饼状图
  // TODO: 添加动态数据
  costClick(e: any) {
    console.log(this.stcost.data)
    this.costPieData =  [
      { value: 251, type: '药品', name: '西药' },
    
      { value: 610, type: '诊疗', name: '治疗费' },
      { value: 434, type: '诊疗', name: '手术费' },
      { value: 335, type: '材料', name: '当归' },
      { value: 250, type: '材料', name: '燕窝' },

    ];
      const d = this.stcost.data.map((da)=>{
        return {
          value:da.AKC057,
          type:da._values[1].text,
          name:da._values[0].text,
        }
      })
      this.costPieData = d;
      console.log(d);
   
    setTimeout(()=>{
        this.costvisible = true;
    },1000) //  延迟加载,
  
    // this.stcost.data.map((d) => {
    //   const x = d._values[0].text
    //   const y = d.AKC057
    //   this.costPieData.push({ x, y })
    // })
    // this.cost.total = `&yen ${this.costPieData.reduce((pre, now) => now.y + pre, 0).toFixed(2)}`
    // console.log('fundPieData :', this.costPieData);
  }
  DeselectFund() {
    // 避免二次检测
    setTimeout(() => {
      this.fundvisible = false;
    }, 100);

  }
  DeselectCost() {
    // 避免二次检测
    setTimeout(() => {
      this.costvisible = false;
    }, 100);

  }

  export() {
    if (this.st.st.total > 1000) {
      this.message.error('数据过多，无法打印');
    }
    else {
      this.st.exportAll();
    }
  }

  open() {
    this.drvisible = true;
  }
  close() {
    this.drvisible = false;
  }


  // 保存条件
  // saveCondition() {
  //   if (!this.textvisible) {
  //     this.textvisible = true;
  //   } else {
  //     const time = new Date()
  //     this.list.push({
  //       title: time.getFullYear() + "-" + (time.getMonth() + 1) + "-" + time.getDate(),
  //       description: this.inputValue,
  //       content: JSON.stringify(this.sf.value)
  //     })
  //     localStorage.setItem('Condition', JSON.stringify(this.list));
  //     this.textvisible = false;
  //   }
  // }


  // 删除条件
  /**
   * nz-list 策略是 onpush 要改变数组的引用
   * @param index 数组下标
   */
  deleteCondition(index:number) {

    const value :string = this.list[index].CZE040;
 
    console.log(this.list)
   
    this.lbservice.lbservice(this.params.delCondition,{para:{CZE040:value}}).then(
      (res)=>{
        if(res.code<1)
          this.message.error(res.errmsg) ; 
          else{
            let arr = this.list
            arr.splice(index,1)
            console.log(arr);
            this.list =[...arr];
            console.log(this.list);

          }   
      }
    )
  }

  // 查询条件赋值
  assignsf(item) {
    if (this.expandForm === false) this.expand();
    const value = JSON.parse(item.CZE042)
    this.formData = value
    this.close()
  }


  // 条件保存
 async save(text:string) {
    const para={
      CZE042:JSON.stringify(this.sf.value) ,
      CZE043:text,
    }

    this.popvisible = false;
   await   this.lbservice.lbservice(this.params.save,{para}).then(
        (res)=>{
          if(res.code<0)
            this.message.error(res.message)
            else
            this.message.success('保存成功')
        }
      )
      this.ConditionQuery();
  }

  //条件数组
  ConditionQuery(){
    this.list =[null];
    this.lbservice.lbservice(this.params.conditionQuery,{}).then(
      (res)=>{
        if(res.code<0)
          this.message.error(res.message)
          else
            {
              const arr =[]
              res.message.list.forEach(element => {
                  arr.push(element) ;
              });
              this.list = arr;
            }
      }
    )
  }
  //分享方法
  shareChange(i){
    console.log('i :', i);
    this.list[i].CZE044 = this.list[i].CZE044 ==='0'? '1':'0';
    const CZE040 =this.list[i].CZE040;
    this.lbservice.lbservice(this.params.share,{para:{CZE040}}).then(
      (res)=>{
        if(res.code<1)
          this.message.error('分享失败')
      }
    )
  }

}